'use client'

import { useState } from 'react'
import { Form, Input, Select, Upload, Button, Card, message, Progress, Space } from 'antd'
import { UploadOutlined, InboxOutlined } from '@ant-design/icons'
import { PRODUCT_TYPES, createEmptyProductForm } from '../types/product'
import { PRODUCT_FORM_FIELDS, validateProductForm, getFieldRules } from '../schemas/productSchema'
import { SimpleUploadProgress } from './UploadProgress'
import { handleUploadError, showSuccess, handleApiError } from '../utils/errorHandler'

const { TextArea } = Input
const { Option } = Select
const { Dragger } = Upload

export default function UploadForm({ onSubmit, loading = false }) {
    const [form] = Form.useForm()
    const [productType, setProductType] = useState(PRODUCT_TYPES.WEBSITE)
    const [fileList, setFileList] = useState([])
    const [thumbnailList, setThumbnailList] = useState([])
    const [uploadProgress, setUploadProgress] = useState(0)

    // 处理产品类型变化
    const handleTypeChange = (value) => {
        setProductType(value)
        // 清除相关字段的值
        if (value === PRODUCT_TYPES.WEBSITE) {
            form.setFieldsValue({ file: null })
            setFileList([])
        } else {
            form.setFieldsValue({ url: '' })
        }
    }

    // 处理文件上传前的验证
    const beforeUpload = (file, fieldName = 'file') => {
        const config = PRODUCT_FORM_FIELDS[fieldName]

        // 检查文件大小
        if (file.size > config.maxSize) {
            const maxSizeMB = config.maxSize / (1024 * 1024)
            handleUploadError(new Error(`文件大小不能超过 ${maxSizeMB}MB`), file.name)
            return false
        }

        // 检查文件类型
        const allowedExtensions = config.accept.split(',').map(ext => ext.trim().toLowerCase())
        const fileExtension = '.' + file.name.split('.').pop().toLowerCase()

        if (!allowedExtensions.includes(fileExtension)) {
            handleUploadError(new Error(`文件格式不支持，请选择 ${config.accept} 格式的文件`), file.name)
            return false
        }

        return false // 阻止自动上传，我们将在表单提交时处理
    }

    // 处理应用文件上传
    const handleFileChange = ({ fileList: newFileList }) => {
        setFileList(newFileList.slice(-1)) // 只保留最新的一个文件
        if (newFileList.length > 0) {
            form.setFieldsValue({ file: newFileList[0].originFileObj })
        } else {
            form.setFieldsValue({ file: null })
        }
    }

    // 处理缩略图上传
    const handleThumbnailChange = ({ fileList: newFileList }) => {
        setThumbnailList(newFileList.slice(-1)) // 只保留最新的一个文件
        if (newFileList.length > 0) {
            form.setFieldsValue({ thumbnail: newFileList[0].originFileObj })
        } else {
            form.setFieldsValue({ thumbnail: null })
        }
    }

    // 处理表单提交
    const handleSubmit = async (values) => {
        try {
            // 客户端验证
            const formData = {
                ...values,
                type: productType,
                file: fileList.length > 0 ? fileList[0].originFileObj : null,
                thumbnail: thumbnailList.length > 0 ? thumbnailList[0].originFileObj : null
            }

            const validation = validateProductForm(formData)
            if (!validation.isValid) {
                // 显示验证错误
                Object.keys(validation.errors).forEach(field => {
                    handleApiError({ response: { status: 400, data: { message: validation.errors[field] } } })
                })
                return
            }

            // 调用父组件的提交函数
            await onSubmit(formData, setUploadProgress)

            // 成功后重置表单，让用户可以继续上传其他产品
            form.resetFields()
            setFileList([])
            setThumbnailList([])
            setProductType(PRODUCT_TYPES.WEBSITE)
            setUploadProgress(0)

        } catch (error) {
            console.error('表单提交错误:', error)
            handleApiError(error, '提交失败，请重试')
        }
    }

    return (
        <Card className="max-w-4xl mx-auto">
            <Form
                form={form}
                layout="vertical"
                onFinish={handleSubmit}
                initialValues={createEmptyProductForm()}
                className="space-y-6"
            >
                {/* 产品标题 */}
                <Form.Item
                    name="title"
                    label={PRODUCT_FORM_FIELDS.title.label}
                    rules={getFieldRules('title')}
                >
                    <Input
                        placeholder={PRODUCT_FORM_FIELDS.title.placeholder}
                        maxLength={PRODUCT_FORM_FIELDS.title.maxLength}
                        showCount
                        size="large"
                    />
                </Form.Item>

                {/* 产品描述 */}
                <Form.Item
                    name="description"
                    label={PRODUCT_FORM_FIELDS.description.label}
                    rules={getFieldRules('description')}
                >
                    <TextArea
                        placeholder={PRODUCT_FORM_FIELDS.description.placeholder}
                        maxLength={PRODUCT_FORM_FIELDS.description.maxLength}
                        showCount
                        rows={4}
                        size="large"
                    />
                </Form.Item>

                {/* 产品类型 */}
                <Form.Item
                    name="type"
                    label={PRODUCT_FORM_FIELDS.type.label}
                    rules={getFieldRules('type')}
                >
                    <Select
                        size="large"
                        onChange={handleTypeChange}
                        placeholder="请选择产品类型"
                    >
                        {PRODUCT_FORM_FIELDS.type.options.map(option => (
                            <Option key={option.value} value={option.value}>
                                {option.label}
                            </Option>
                        ))}
                    </Select>
                </Form.Item>

                {/* 条件字段：网站链接 */}
                {productType === PRODUCT_TYPES.WEBSITE && (
                    <Form.Item
                        name="url"
                        label={PRODUCT_FORM_FIELDS.url.label}
                        rules={getFieldRules('url', { type: productType })}
                    >
                        <Space.Compact style={{ display: 'flex', width: '100%' }}>
                            <Button size="large" disabled style={{ minWidth: '50px' }}>
                                🌐
                            </Button>
                            <Input
                                placeholder={PRODUCT_FORM_FIELDS.url.placeholder}
                                size="large"
                                style={{ flex: 1 }}
                            />
                        </Space.Compact>
                    </Form.Item>
                )}

                {/* 条件字段：应用文件上传 */}
                {productType === PRODUCT_TYPES.APP && (
                    <Form.Item
                        name="file"
                        label={PRODUCT_FORM_FIELDS.file.label}
                        rules={getFieldRules('file', { type: productType })}
                    >
                        <Dragger
                            fileList={fileList}
                            onChange={handleFileChange}
                            beforeUpload={(file) => beforeUpload(file, 'file')}
                            accept={PRODUCT_FORM_FIELDS.file.accept}
                            maxCount={1}
                        >
                            <p className="ant-upload-drag-icon">
                                <InboxOutlined />
                            </p>
                            <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
                            <p className="ant-upload-hint">
                                支持格式: {PRODUCT_FORM_FIELDS.file.accept}，最大 100MB
                            </p>
                        </Dragger>
                    </Form.Item>
                )}

                {/* 缩略图上传（可选） */}
                <Form.Item
                    name="thumbnail"
                    label={PRODUCT_FORM_FIELDS.thumbnail.label}
                    extra="可选，支持 JPG、PNG、GIF、WebP 格式，最大 5MB"
                >
                    <Upload
                        listType="picture-card"
                        fileList={thumbnailList}
                        onChange={handleThumbnailChange}
                        beforeUpload={(file) => beforeUpload(file, 'thumbnail')}
                        accept={PRODUCT_FORM_FIELDS.thumbnail.accept}
                        maxCount={1}
                    >
                        {thumbnailList.length === 0 && (
                            <div>
                                <UploadOutlined />
                                <div style={{ marginTop: 8 }}>上传缩略图</div>
                            </div>
                        )}
                    </Upload>
                </Form.Item>

                {/* 上传进度 */}
                {uploadProgress > 0 && uploadProgress < 100 && (
                    <div className="mb-4">
                        <SimpleUploadProgress
                            progress={uploadProgress}
                            status="active"
                            fileName={fileList.length > 0 ? fileList[0].name : ''}
                        />
                    </div>
                )}

                {/* 提交按钮 */}
                <Form.Item>
                    <div className="flex gap-4 justify-center">
                        <Button
                            type="default"
                            size="large"
                            onClick={() => {
                                form.resetFields()
                                setFileList([])
                                setThumbnailList([])
                                setProductType(PRODUCT_TYPES.WEBSITE)
                            }}
                        >
                            重置表单
                        </Button>
                        <Button
                            type="primary"
                            htmlType="submit"
                            size="large"
                            loading={loading}
                            className="min-w-32"
                        >
                            {loading ? '上传中...' : '提交产品'}
                        </Button>
                    </div>
                </Form.Item>
            </Form>
        </Card>
    )
}